package org.example.chapter1;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.example.entity.User;
import org.example.util.Util;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * 用 Fastjson 序列化对象
 * 并保存到 redis 中，使用 KV、HASH 结构
 */
@Data
public class HW1_2_5_KV_Hash {
    public static void main(String[] args) {
        testKV();
        testHash();
    }

    public static void testHash() {
        Long id = 1L;
        String name = "alice";
        Integer age = 18;
        String fieldAge = "age";
        String fieldName = "name";
        String key = String.format("Id_%d", id);

        System.out.println("before set hash: " + fieldAge + ": " + getUserWithRedisHash(key));
        Map<String, String> param = new HashMap<>();
        param.put(fieldAge, age.toString());
        setUserWithRedisHash(key, param);
        System.out.println("after set hash: " + fieldAge + ": " + getUserWithRedisHash(key));
        param.remove(fieldAge);
        param.put(fieldName, name);
        setUserWithRedisHash(key, param);
        System.out.println("after set hash: " + fieldName + ": " + getUserWithRedisHash(key));
    }

    public static void testKV() {
        Long id = 1L;
        String name = "alice";
        Integer age = 18;

        User user = new User(id, name, age);
        System.out.println("before set: " + getUserWithRedisKV(id));
        setUserWithRedisKV(user);
        System.out.println("after set: " + getUserWithRedisKV(id));
    }

    public static User getUserWithRedisKV(Long id) {
        Jedis jedis = Util.getJedis();
        String u = jedis.get(id.toString());
        if (u == null || u.isEmpty()) {
            return null;
        }
        return JSON.parseObject(u, User.class);
    }

    public static void setUserWithRedisKV(User user) {
        Jedis jedis = Util.getJedis();
        String t = JSON.toJSONString(user);
        jedis.set(user.getId().toString(), t);
    }

    public static Map<String, String> getUserWithRedisHash(String key) {
        Jedis jedis = Util.getJedis();
        return jedis.hgetAll(key);
    }

    public static void setUserWithRedisHash(String key, Map<String, String> param) {
        Jedis jedis = Util.getJedis();
        jedis.hset(key, param);
    }
}
